const globalCode = require('../../codes/global')
const jwt = require('jsonwebtoken')
const globalConfigs = require('../../configs')
const log = require('../../utils/log')
const routes = require('../routes')

function checkRouteExist(path) {
  const route = routes.stack.find(route => route.path === path);
  return route
}

const globalInterceptor = {
  async errorInterceptor(ctx, next) {
    try {
      await next();  // 执行其他中间件
    } catch (err) {
      // 捕获错误并返回自定义错误响应
      log.logError(err);  // 可以记录错误
      ctx.status = err.status || 500;
      ctx.body = {
        msg: globalCode.ERROR_INTERNAL_ERROR,
        success: false
      };
    }
  },
  /**
   * 判断用户的登录状态
   * @param {*} ctx 
   * @param {*} next 
   * @returns 
   */
  async authInterceptor (ctx, next) {
    try {
      // 如果是登录接口，则直接放行， 不需要通过
      if (ctx.url === '/users/login') {
        await next()
        return
      }
      if (!ctx.request.header.authorization) {
        ctx.status = 401,
        ctx.body = {
          success: false,
          msg: globalCode.ERROR_NO_AUTHTICATION
        }
        return
      }
      const authHeader = ctx.headers['authorization'];
      const token = authHeader.split(' ')[1]
      try {
        const decoded = jwt.verify(token, globalConfigs.secret);
        ctx.state.user = decoded;
      } catch {
        ctx.status = 401;
        ctx.body = {
          success: false,
          message: globalCode.ERROR_AUTHENTICATION_EXPIRED
        }
        return
      }
      await next()
    } catch (error) {
      return Promise.reject(error)
    }
  },
  /**
   * 最终的中间件，判断api是否是404或者是方法不正确
   */
  async isNotFoundRouter(ctx) {
    const checkRoute = checkRouteExist(ctx.url)
    if (checkRoute) {
      ctx.body = {
        success: false,
        msg: `仅支持${checkRoute.methods.join(',')}方法`
      }
      log.logError(`用户请求路劲错误,url:${ctx.url}, method:${ctx.request.method}`)
      return
    }
    ctx.body = {
      success: false,
      msg: '请求路劲不存在'
    }
  }
}

module.exports = globalInterceptor